import 'dart:io';

import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mfkb/pages/root.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/UserService.dart';
import 'package:simple_image_crop/simple_image_crop.dart';
import 'package:toast/toast.dart';

enum _sheetType { gallery, camera }
File _image = null ;

class UserFullDataPage extends StatefulWidget {
  @override
  _UserFullDataPageState createState() => _UserFullDataPageState();
}

class _UserFullDataPageState extends State<UserFullDataPage> {

  var _file = null ;
  var _nickname = null ;
  var _phone = null ;
  var _icon = null ;

  bool _can_upload = false ;

  final cropKey = GlobalKey<ImgCropState>();

  var gender = 1 ;

  Future getImage(type) async {
    File image = await ImagePicker.pickImage(
        source: type == _sheetType.gallery
            ? ImageSource.gallery
            : ImageSource.camera);
    if (image == null) return;
    Navigator.of(context).pop();
    var i = await Navigator.of(context).push(MaterialPageRoute(builder: (_){
      return SimpleCropRoute(image) ;
    })) ; //pushNamed('crop_page', arguments: {'image': image});
    if(i != null){
      if(_nickname != null && _phone != null && _image != null){
        setState(() {
          _can_upload = true ;
        });
      }else{
        setState(() {
          _can_upload = false ;
        });
      }
    }
  }

  void _showActionSheet() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min, // 设置最小的弹出
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机拍照"),
                onTap: () async {
                  getImage(_sheetType.camera);
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册选择"),
                onTap: () async {
                  getImage(_sheetType.gallery);
                },
              ),
            ],
          ),
        );
      });
  }

  buildCircle(){
    if(_image == null){
      return CircleAvatar(
        radius: 100,
        backgroundColor: Color.fromARGB(255, 236, 237, 241) ,
        child: Container(
          width: ScreenUtil().setWidth(40),
          height: ScreenUtil().setWidth(40),
          margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
          child: Image.asset("assets/images/photo.png"),
        ),
      ) ;
    }else{
      return CircleAvatar(
        radius: 100 ,
        backgroundColor:  Color.fromARGB(255, 236, 237, 241) ,
        backgroundImage: FileImage(_image) ,
      ) ;
    }
  }

  @override
  Widget build(BuildContext context) {

    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark,
      child: Scaffold(
        body: Container(
          width: ScreenUtil().setWidth(375),
          height: ScreenUtil().setHeight(812),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Color.fromARGB(255, 255, 255, 255) ,
                Color.fromARGB(255, 246, 245, 248)
              ] ,
              begin: Alignment.bottomRight ,
              end: Alignment.topLeft
            )
          ),
          child: ScrollConfiguration(
            behavior: MyBehavior() ,
            child: ListView(
              children: <Widget>[
                GestureDetector(
                  child:Container(
                    width: ScreenUtil().setWidth(100),
                    height: ScreenUtil().setWidth(100),
                    margin: EdgeInsets.only(top:ScreenUtil().setHeight(54) , left:ScreenUtil().setWidth(138) , right:ScreenUtil().setWidth(137)),
                    // decoration: BoxDecoration(
                    //   color: Colors.red ,
                    // ),
                    child: SizedBox(
                      width: ScreenUtil().setWidth(100),
                      height: ScreenUtil().setHeight(100),
                      child: buildCircle() 
                    )
                  ) ,
                  onTap: (){
                    _showActionSheet() ;
                  },
                ) ,
                Container(
                  width: ScreenUtil().setHeight(100),
                  height: 15,
                  margin: EdgeInsets.only(top:ScreenUtil().setHeight(11)),
                  child: Text("上传头像" , style: TextStyle(
                    fontSize: 12 ,
                    color: Color.fromARGB(255, 121, 132, 155)
                  ),textAlign: TextAlign.center,),
                ) ,
                Container(
                  height: ScreenUtil().setHeight(56),
                  margin: EdgeInsets.only(top:ScreenUtil().setHeight(32) , left:ScreenUtil().setWidth(28) , right:ScreenUtil().setWidth(27)),
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        child: Container(
                          width: ScreenUtil().setWidth(150),
                          height: ScreenUtil().setHeight(56),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(15)) ,
                            color:Colors.white ,
                            border: Border.all(
                              color: gender == 1 ? Color.fromARGB(255, 0, 195, 206)  : Color.fromARGB(255, 236, 237, 241) ,
                              style: BorderStyle.solid ,
                              width: 1
                            ) ,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                width:ScreenUtil().setWidth(32) ,
                                height: ScreenUtil().setHeight(32) ,
                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(26)),
                                child: Image.asset("assets/images/boy.png"),
                              ) ,
                              Container(
                                height: 22 ,
                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(17)),
                                child: Text("男生" , style: TextStyle(
                                  fontSize: 16 ,
                                  fontFamily: "PingFangSC-Semibold,PingFang SC" ,
                                  fontWeight: FontWeight.w600 ,
                                  height: 1.3
                                ),),
                              )
                            ],
                          ),
                        ) ,
                        onTap: (){
                          setState(() {
                            gender = 1 ;
                          });
                        },
                      ) ,
                      GestureDetector(
                        child: Container(
                          width: ScreenUtil().setWidth(150),
                          height: ScreenUtil().setHeight(56),
                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(20)),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(15)) ,
                            color:Colors.white ,
                            border: Border.all(
                              color: gender == 0 ? Color.fromARGB(255, 0, 195, 206)  : Color.fromARGB(255, 236, 237, 241) , 
                              style: BorderStyle.solid ,
                              width: 1
                            ) ,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                width:ScreenUtil().setWidth(32) ,
                                height: ScreenUtil().setHeight(32) ,
                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(26)),
                                child: Image.asset("assets/images/girl.png"),
                              ) ,
                              Container(
                                height: 22 ,
                                margin: EdgeInsets.only(left:ScreenUtil().setWidth(17)),
                                child: Text("女生" , style: TextStyle(
                                  fontSize: 16 ,
                                  fontFamily: "PingFangSC-Semibold,PingFang SC" ,
                                  fontWeight: FontWeight.w600 ,
                                  height: 1.3
                                ),),
                              )
                            ],
                          ),
                        ) ,
                        onTap: () {
                          setState(() {
                            gender = 0 ;
                          });
                        },
                      )
                    ],
                  ),
                ) ,
                item("assets/images/nickname.png" , "请输入昵称" , 29 , false , (value){
                  _nickname = value ;
                  if(_nickname != null && _phone != null && _image != null){
                    setState(() {
                      _can_upload = true ;
                    });
                  }else{
                    setState(() {
                      _can_upload = false ;
                    });
                  }
                }) ,
                item("assets/images/phone.png" , "请输入手机号" , 14 , true , (value){
                  _phone = value ;
                  if(_nickname != null && _phone != null && _image != null){
                    setState(() {
                      _can_upload = true ;
                    });
                  }else{
                    setState(() {
                      _can_upload = false ;
                    });
                  }
                }) ,
                GestureDetector(
                  child: Container(
                    height: ScreenUtil().setHeight(48),
                    margin: EdgeInsets.only(left:ScreenUtil().setWidth(25) , right:ScreenUtil().setWidth(24) , top:ScreenUtil().setHeight(32)),
                    decoration: BoxDecoration(
                      color:_can_upload ? Color.fromARGB(255, 0, 195, 206) : Color.fromARGB(255, 205, 207, 221) ,
                      borderRadius: BorderRadius.all(Radius.circular(10)) ,
                    ),
                    child: Center(
                      child: Text("完成"),
                    ),
                  ),
                  onTap: () async{
                    if(_can_upload){
                      int len = _image.lengthSync() ;
                      if(len > 1024*1024*9){
                        Toast.show("文件太大", context) ;
                        return ;
                      }
                      File img = null ;
                      img = await FlutterNativeImage.compressImage(
                        _image.path ,
                        // quality: 80 ,
                        // percentage: 30 
                      ) ;
                      bool flag = await UserService().userinfo(img , _nickname , _phone , gender) ;
                      if(flag){
                        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
                          return NavitorBar() ;
                        })) ;
                      }else{
                        Toast.show("保存失败", context) ;
                      }
                    }
                  },
                )
              ],
            )
          ),
        ),
      ),
    ) ;
  }

  item(String icon , String txt , int top , bool phone , var onChange){
    return Container(
      height: ScreenUtil().setHeight(50),
      margin: EdgeInsets.only(left:ScreenUtil().setWidth(28) , right:ScreenUtil().setWidth(27) , top:ScreenUtil().setHeight(top)),
      decoration: BoxDecoration(
        color: Colors.white ,
        borderRadius: BorderRadius.all(Radius.circular(10)) ,
        border: Border.all(
          color: Color.fromARGB(255, 236, 237, 241) ,
          width:1 ,
          style:BorderStyle.solid
        ) ,
      ),
      child: Row(
        children: <Widget>[
          Container(
            height: ScreenUtil().setWidth(16),
            width: ScreenUtil().setWidth(16),
            margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
            child: Image.asset(icon),
          ) ,
          Expanded(
            child: Container(
              height: ScreenUtil().setWidth(30),
              margin: EdgeInsets.only(left:ScreenUtil().setWidth(39)),
              child: TextField(
                keyboardType: phone ? TextInputType.phone : TextInputType.text ,
                decoration: InputDecoration(
                  border: InputBorder.none ,
                  hintText: txt ,
                  hintStyle: TextStyle(
                    fontSize: 16 ,
                    height:1.05
                  )
                ),
                onChanged: (value){
                  if(onChange != null){
                    onChange(value) ;
                  }
                },
              ),
            ) ,
          )
        ],
      ),
    ) ;
  }
}


class SimpleCropRoute extends StatefulWidget {
  File image ;
  File _image ;

  SimpleCropRoute(@required this.image) ;

  @override
  _SimpleCropRouteState createState() => _SimpleCropRouteState();
}

class _SimpleCropRouteState extends State<SimpleCropRoute> {
  final cropKey = GlobalKey<ImgCropState>();

  Future<Null> showImage(BuildContext context, File file) async {
    new FileImage(file)
        .resolve(new ImageConfiguration())
        .addListener(ImageStreamListener((ImageInfo info, bool _) {
      print('-------------------------------------------$info');
    }));
    _image = file ;
    widget._image = file ;
    setState(() {
      Navigator.of(context).pop(widget._image) ;
    });
  }

  @override
  Widget build(BuildContext context) {
    final Map args = ModalRoute.of(context).settings.arguments;
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          title: Text(
            '头像截取',
            style: TextStyle(color: Colors.black),
          ),
          backgroundColor: Colors.white,
          leading: new IconButton(
            icon:
                new Icon(Icons.navigate_before, color: Colors.black, size: 40),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: Center(
          child: ImgCrop(
            key: cropKey,
            //chipRadius: 200,
            //chipShape: 'circle',
            maximumScale: 3,
            image: FileImage(widget.image),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () async {
            final crop = cropKey.currentState;
            final croppedFile =
                await crop.cropCompleted(widget.image, pictureQuality: 600);
            showImage(context, croppedFile);
          },
          backgroundColor: Colors.white ,
          tooltip: 'Increment',
          child: Text('确认' , style: TextStyle(color: Colors.green),),
        ));
  }
}